package com.secxiot.consumer.user.service;

import com.secxiot.common.constant.ServerStatusEnum;
import com.secxiot.common.exception.BaseRuntimeException;
import com.secxiot.consumer.user.feign.UserClient;
import com.secxiot.provider.user.dto.DeptDto;
import com.secxiot.provider.user.entity.UserDo;
import com.secxiot.provider.user.vo.DeptVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class DeptConsumerService {

    @Autowired
    private UserClient userClient;

    public List<DeptVo> getUserDeptSubs(Long userId) {
        UserDo user = userClient.getUser(userId);
        if (user.getDeptId() == null) {
            throw new BaseRuntimeException(ServerStatusEnum.NO_DEPT);
        }
        List<DeptVo> depts = new ArrayList<>();
        List<DeptDto> dpts = userClient.listToLeafByDeptId(user.getDeptId());
        for (DeptDto dpt : dpts) {
            depts.add(new DeptVo(dpt));
        }
        return  depts;
/*        //部门范围
        DeptDto userDept = userClient.getDeptByDeptId(user.getDeptId());
        String[] supperIds = userDept.getSupperIds().split("-");
        int deptLevel = 1;
        int userDeptLevel = userDept.getDeptLevel();
        if (deptId == null) {
            //首先是直属部门
            deptId = userDept.getParentId();
            deptLevel = userDept.getDeptLevel() - 1;
        } else {
            deptLevel = userClient.getDeptByDeptId(deptId).getDeptLevel();
        }

        if (deptLevel < userDeptLevel - 1) {
            //条件部门级别高于用户归属部门级别，则只返回条件部门下级部门中该用户所归属的部门
            DeptDto deptDto = userClient.getDeptByDeptId(Long.parseLong(supperIds[deptLevel + 1]));
            DeptVo deptVo = new DeptVo(deptDto);
            depts.add(deptVo);
        } else if(deptLevel == userDeptLevel - 1) {
            //条件部门级别高于用户归属部门级别，则只返回条件部门下级部门中该用户所归属的部门
            DeptDto deptDto = userClient.getDeptByDeptId(userDept.getDeptId());
            DeptVo deptVo = new DeptVo(deptDto);
            depts.add(deptVo);
        } else {
            List<DeptDto> deptDtos = userClient.listSubdeptByDeptId(deptId);
            List<DeptVo> collect = deptDtos.stream().map(deptDto -> new DeptVo(deptDto)).collect(Collectors.toList());
            depts.addAll(collect);
        }
        return depts;*/
    }
}
